package cn.kawa.controller;


import cn.kawa.domain.User;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private RestTemplate restTemplate;

    /**
     * 使用restTemplate+ribbon的方式调用user服务的接口
     * @param id
     * @return
     */
    // user/getById/1
    @GetMapping("/getById/{id}")
    @HystrixCommand(fallbackMethod = "fallbackGetById")
    public User getById(@PathVariable("id") Long id){
        //return new User(1L,"胡桃","森罗谷");//测试输出
        //String url="http://localhost:10020/user/getById/"+id;//[已弃用]
//        long timeMillis1 = System.currentTimeMillis();//[计算加载时间，已弃用]
        //拿到客户端名称，相当于拿到所有节点
        String url="http://user-server/user/getById/"+id;
        // restTemplate的getForObject方法，参数1：访问地址，参数2：要返回的值
        User forObject = restTemplate.getForObject(url, User.class);
//        long timeMillis2 = System.currentTimeMillis();//[计算加载时间，已弃用]
//        System.out.println(timeMillis2-timeMillis1);//[计算加载时间，已弃用]
        return forObject;//尝试计算调用时间,引出饥饿加载
    }

    /**
     * 兜底方案
     * 真正的接口调用报错后会走这里 ：上面的user调用失败的情况
     * @param id
     * @return
     */
    public User fallbackGetById(@PathVariable("id") Long id){

        return new User(-1L,"无","用户服务不可到达");//尝试计算调用时间,引出饥饿加载
    }

}